package com.lanou3g.code0420;

import java.io.*;
import java.net.Socket;

/**
 * Created by dllo on 18/4/20.
 */
public class EchoThread extends Thread{
    private Socket client; //每个线程连接自己的客户端

    public EchoThread(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {

        BufferedReader reader = null;
        PrintWriter pw = null;
        try {
            OutputStream os = client.getOutputStream();
            InputStream is = client.getInputStream();   // 从客户端读取的是字符数组

            reader = new BufferedReader(new InputStreamReader(is));
            pw = new PrintWriter(new OutputStreamWriter(os));

            String line = "";

            // 循环的终止条件是客户端断开
            while ((line = reader.readLine()) != null){
                String echo = "ECHO:"+line;
                pw.println(echo);
                pw.flush();  //如果没有写满buff 8016，强制发送过去

            }


        } catch (Exception e) {
            // 如果进到catch中，就说明客户端断开了
            System.out.println("客户端断开");

        }finally {

            if (pw != null){
                pw.close();
            }
            if (reader != null){
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (client != null){
                try {
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }


    }
}
